package sum.book.auth.server.service.impl;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.stereotype.Service;
import sum.book.common.redis.utils.RedisRepository;

import java.util.concurrent.TimeUnit;

@Service
public class RedisAuthorizationCodeServicesImpl extends RandomValueAuthorizationCodeServices {

    String AUTH_CODE_PREFIX = "book:auth:code:";

    private RedisRepository redisRepository;

    private RedisSerializer<Object> valueSerializer;

    public RedisAuthorizationCodeServicesImpl(RedisRepository redisRepository) {
        this.redisRepository = redisRepository;
        this.valueSerializer = RedisSerializer.java();
    }


    /**
     * 将存储code到redis，并设置过期时间，10分钟
     */
    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        redisRepository.set(redisKey(code), authentication, 10, TimeUnit.MINUTES,valueSerializer);
    }

    @Override
    protected OAuth2Authentication remove(final String code) {
        String codeKey = redisKey(code);
        OAuth2Authentication token = (OAuth2Authentication) redisRepository.get(codeKey,valueSerializer);
        redisRepository.del(codeKey);
        return token;
    }

    /**
     * redis中 code key的前缀
     */
    private String redisKey(String code) {
        return AUTH_CODE_PREFIX + code;
    }
}
